package org.example.chat_room.api;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.ICaptcha;
import cn.hutool.captcha.LineCaptcha;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.example.chat_room.model.CaptchaProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;

@RestController
public class CaptchaAPI {
    @Autowired
    private CaptchaProperties captchaProperties;

    private static long VALID_TIME = 60*1000;

    @RequestMapping("/getCaptcha")
    public void getCaptcha(HttpSession session, HttpServletResponse response){
        ICaptcha captcha = CaptchaUtil.createLineCaptcha(captchaProperties.getWidth(), captchaProperties.getHeight());
        try {
            captcha.write(response.getOutputStream());
//            禁止缓存
            response.setHeader("Pragma","no-cache");
//            设置返回类型
            response.setContentType("image/jpeg");
            session.setAttribute(captchaProperties.getSession().getCode(), captcha.getCode());
            session.setAttribute(captchaProperties.getSession().getDate(), System.currentTimeMillis());
//            打印验证码
            System.out.println(captcha.getCode());
            response.getOutputStream().close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @RequestMapping("/checkCaptcha")
    public Boolean checkCaptcha(String captchaCode,HttpSession session) {
        if (!StringUtils.hasLength(captchaCode)){
            return false;
        }
        String sessionCode = (String)session.getAttribute(captchaProperties.getSession().getCode());
        Long sessionDate = (Long)session.getAttribute(captchaProperties.getSession().getDate());
        if (captchaCode.equalsIgnoreCase(sessionCode)
                && (sessionDate != null)
                && ((System.currentTimeMillis() - sessionDate) < VALID_TIME)) {
            return true;
        }
//        设置一个万能验证码
//        if (captchaCode.equalsIgnoreCase("26588")){
//            return true;
//        }
        return false;
    }
}
